package com.longchain.business.search;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.longchain.R;
import com.longchain.common.base.BaseActivity;
import com.longchain.common.base.LongchainApplication;
import com.longchain.manager.AccountManager;
import com.longchain.manager.FileManager;
import com.longchain.manager.entity.FileListResult;
import com.longchain.manager.entity.SearchResult;
import com.tsy.sdk.myokhttp.response.GsonResponseHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 28367 on 2018/3/24.
 */

public class SearchActivity extends BaseActivity{
    private static final String TAG ="SearchActivity" ;
    public static final String FROM ="from" ;
    String from = "";
    @BindView(R.id.search_edit)
    EditText mEditSearch;

    @BindView(R.id.tv_item_one)
    TextView tv_item_one;

    @BindView(R.id.tv_item_two)
    TextView tv_item_two;

    @BindView(R.id.tv_item_three)
    TextView tv_item_three;

    @BindView(R.id.icon1)
    ImageView icon1;

    @BindView(R.id.icon2)
    ImageView icon2;

    @BindView(R.id.icon3)
    ImageView icon3;

    @BindView(R.id.icon4)
    ImageView icon4;

    @BindView(R.id.icon5)
    ImageView icon5;

    @BindView(R.id.icon6)
    ImageView icon6;

    @BindView(R.id.myViewPager)
    ViewPager myViewPager;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    @BindView(R.id.no_history)
    TextView mNoHistoryView;

    @BindView(R.id.clear_all_history)
    TextView mClearHistoryView;

    @BindView(R.id.search_history)
    TextView mSearchHistoryView;

    @BindView(R.id.history_layout)
    View mSearchHistoryLayout;

    @BindView(R.id.tab_layout)
    View mTabLayout;

    private List<Fragment> list;
    private TabFragmentPagerAdapter adapter;
    BaseSearchFragment searchAllFragment;
    BaseSearchFragment searchImageFragment;
    BaseSearchFragment searchVideoFragment;
    BaseSearchFragment searchAudioFragment;
    BaseSearchFragment searchDocFragment;
    BaseSearchFragment searchOtherFragment;
    List<String> historyList;
    HistoryAdapter mHistoryAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        from = getIntent().getStringExtra(FROM);
        if (!TextUtils.isEmpty(from)){
            myViewPager.setVisibility(View.VISIBLE);
            mTabLayout.setVisibility(View.VISIBLE);
            mSearchHistoryLayout.setVisibility(View.GONE);
            switch (from){
                case FileManager.STATUS_ALL:
                    myViewPager.setCurrentItem(0);
                    break;
                case FileManager.STATUS_TEXT:
                    myViewPager.setCurrentItem(1);
                    break;
                case FileManager.STATUS_IMAGE:
                    myViewPager.setCurrentItem(2);
                    break;
                case FileManager.STATUS_VIDEO:
                    myViewPager.setCurrentItem(3);
                    break;
                case FileManager.STATUS_AUDIO:
                    myViewPager.setCurrentItem(4);
                    break;
                default:
                    myViewPager.setCurrentItem(0);
                    break;
            }

            getFileListByType();

        }else {
            mTabLayout.setVisibility(View.GONE);
            myViewPager.setVisibility(View.GONE);
        }
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mHistoryAdapter =new HistoryAdapter(this, historyList, new HistoryAdapter.OnHistoryClick() {
            @Override
            public void onDeleteClick(int position) {
                if (position<historyList.size()){
                    SearchHistoryController.deleteHistory(historyList.get(position));
                    historyList.remove(position);
                    updateHistoryView();
                    mHistoryAdapter.setmTitles(historyList);
                }
            }

            @Override
            public void onItemClick(int position) {

                search(historyList.get(position));
                hideKeyboard();
            }
        });
        mRecyclerView.setAdapter(mHistoryAdapter);

        updateHistoryView();


        mEditSearch.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    // 先隐藏键盘
                    hideKeyboard();
                    String key = mEditSearch.getText().toString();

                    search(key);
                }
                return false;
            }
        });

        myViewPager.setOffscreenPageLimit(6);
        myViewPager.addOnPageChangeListener(new MyPagerChangeListener());

//把Fragment添加到List集合里面
        list = new ArrayList<>();
        searchAllFragment = new SearchAllFragment();
       searchAudioFragment = new SearchMusicFragment();
       searchDocFragment = new SearchDocumentFragment();
       searchImageFragment = new SearchImageFragment();
       searchVideoFragment = new SearchVideoFragment();
       searchOtherFragment = new SearchOtherFragment();
        list.add(searchAllFragment);
        list.add(searchDocFragment);
        list.add(searchImageFragment);
        list.add(searchVideoFragment);
        list.add(searchAudioFragment);
        list.add(searchOtherFragment);
        adapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), list);
        myViewPager.setAdapter(adapter);
        resetSelectIcon();
        icon1.setVisibility(View.VISIBLE);


    }

    private void hideKeyboard() {
        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private void updateHistoryView() {
        if (historyList==null || historyList.size()==0){
            mNoHistoryView.setVisibility(View.VISIBLE);
            mClearHistoryView.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.GONE);
            mSearchHistoryView .setVisibility(View.GONE);
        }else {
            mNoHistoryView.setVisibility(View.GONE);
            mClearHistoryView.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.VISIBLE);
            mSearchHistoryView .setVisibility(View.VISIBLE);
        }
    }

    private void getFileListByType(){
        Map params = new HashMap<>();
        int page = 1;
        params.put("role", from);
        params.put("page", String.valueOf(page));
        params.put("pageSize", String.valueOf(20));
        LongchainApplication.getInstance().getMyOkHttp().get().url("/nas/file/list").params(params).tag(this).addHeader("Authorization", AccountManager.token).enqueue(new GsonResponseHandler<FileListResult>() {

            @Override
            public void onSuccess(int i, FileListResult searchResult) {

//                Toast.makeText(SearchActivity.this,searchResult.toString(),Toast.LENGTH_SHORT).show();
                switch (from){
                    case FileManager.STATUS_ALL:
                        searchAllFragment.updateData(searchResult.getData().getFiles());
                        break;
                    case FileManager.STATUS_TEXT:
                        searchDocFragment.updateData(searchResult.getData().getFiles());
                        break;
                    case FileManager.STATUS_IMAGE:
                        searchImageFragment.updateData(searchResult.getData().getFiles());
                        break;
                    case FileManager.STATUS_VIDEO:
                        searchVideoFragment.updateData(searchResult.getData().getFiles());
                        break;
                    case FileManager.STATUS_AUDIO:
                        searchAudioFragment.updateData(searchResult.getData().getFiles());
                        break;
                    default:
                        searchAllFragment.updateData(searchResult.getData().getFiles());
                        break;
                }


            }


            @Override
            public void onFailure(int statusCode, String error_msg) {
                Toast.makeText(SearchActivity.this,"加载失败，原因："+error_msg+statusCode,Toast.LENGTH_SHORT).show();

            }
        });

    }


    private String mCurrentKey;
    private void search(String key) {
        mCurrentKey = key;
        myViewPager.setVisibility(View.VISIBLE);
        mTabLayout.setVisibility(View.VISIBLE);
        mSearchHistoryLayout.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(key)){
            String fileType = getSearchFileType();

            Map params = new HashMap<>();
            int page = 1;
            params.put("name", key);
            params.put("role",fileType);
            params.put("page", String.valueOf(page));
            params.put("pageSize", String.valueOf(20));
            LongchainApplication.getInstance().getMyOkHttp().get().url("/nas/search/").params(params).tag(this).addHeader("Authorization", AccountManager.token).enqueue(new GsonResponseHandler<FileListResult>() {

                @Override
                public void onSuccess(int i, FileListResult searchResult) {
                    Log.d(TAG,"search success :"+searchResult.toString());

                    ((BaseSearchFragment)adapter.getItem(myViewPager.getCurrentItem())).updateData(searchResult.getData().getFiles());
                }


                @Override
                public void onFailure(int statusCode, String error_msg) {
                    Toast.makeText(SearchActivity.this,"搜索失败，原因："+error_msg+statusCode,Toast.LENGTH_SHORT).show();

                }
            });

            SearchHistoryController.insertSearchKeyToSP(key);
        }
    }

    @NonNull
    private String getSearchFileType() {

        int arg0 = myViewPager.getCurrentItem();
        switch (arg0) {
            case 0:
                return FileManager.STATUS_ALL;

            case 1:
                return FileManager.STATUS_TEXT;

            case 2:
                return FileManager.STATUS_IMAGE;

            case 3:
                return FileManager.STATUS_VIDEO;

            case 4:
                return FileManager.STATUS_AUDIO;

            case 5:
                return FileManager.STATUS_ALL;

        }
        return  FileManager.STATUS_ALL;
    }

    @Override
    protected void initData() {

        historyList = SearchHistoryController.getHistorySearchKey();


    }

    @OnClick({R.id.cancel,R.id.clear_all_history,R.id.tv_item_one,
            R.id.tv_item_two,R.id.tv_item_three,R.id.tv_item_four,R.id.tv_item_five,R.id.tv_item_six})
    public void onViewClicked(View view){
        switch (view.getId()) {
            case R.id.cancel:
                finish();
                break;
            case R.id.tv_item_one:
                myViewPager.setCurrentItem(0);
                break;
            case R.id.tv_item_two:
                myViewPager.setCurrentItem(1);
                break;
            case R.id.tv_item_three:
                myViewPager.setCurrentItem(2);
                break;
            case R.id.tv_item_four:
                myViewPager.setCurrentItem(3);
                break;
            case R.id.tv_item_five:
                myViewPager.setCurrentItem(4);
                break;
            case R.id.tv_item_six:
                myViewPager.setCurrentItem(5);
                break;
            case R.id.clear_all_history:
                SearchHistoryController.clearAllHistory();
                historyList = null;
                updateHistoryView();
                Toast.makeText(this,"清除历史记录成功",Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void resetSelectIcon(){
        icon1.setVisibility(View.GONE);
        icon2.setVisibility(View.GONE);
        icon3.setVisibility(View.GONE);
        icon4.setVisibility(View.GONE);
        icon5.setVisibility(View.GONE);
        icon6.setVisibility(View.GONE);
    }

    public class MyPagerChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            switch (arg0) {
                case 0:
                    resetSelectIcon();
                    icon1.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    resetSelectIcon();
                    icon2.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    resetSelectIcon();
                    icon3.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    resetSelectIcon();
                    icon4.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    resetSelectIcon();
                    icon5.setVisibility(View.VISIBLE);
                    break;
                case 5:
                    resetSelectIcon();
                    icon6.setVisibility(View.VISIBLE);
                    break;
            }

            if (!TextUtils.isEmpty(mCurrentKey)){
                search(mCurrentKey);
            }
        }
    }
}
